import React, { Component } from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity,
  Platform,
  ScrollView,
  DeviceEventEmitter,
} from 'react-native';
import Picker from 'react-native-picker';
import PxToDp from '../../utils/PxToDp';
import FontFamilys from '../../utils/FontFamilys';
import FoursStore from '../../containers/FoursStoreContainer';
import EditProfile from '../../containers/EditProfileContainer';
import fetchProfileAllInfo from '../../actions/profileAllAction';
import { fetchPerformance, fetchFirm } from '../../actions/MysAction';
import { fetchUserInfo } from '../../actions/loginActions';
import { fetchSaleList, fetchMyCustomerList, fetchOtherList } from '../../actions/SaleListActions';
import { fetchOVerviewChannel, fetchImportOVerview } from '../../actions/ImportOverviewAction';
import ModifyEmail from './ModifyEmail';
import ModifyPwd from './ModifyPwd';
import Feedback from './Feedback';
import Login from '../../containers/LoginContainer';
import CommonStorage from '../../utils/CommonStorage';
import Request from '../../utils/request';


import { fetchStoreInfo } from '../../actions/myAction';

/* global host */

const firmList = [{ name: '广汽丰田', id: 103 }, { name: '长安汽车', id: 117 }];
let firmListNew = [];

class List extends Component {
  render() {
    return (
      <View>
        <View style={styles.hLine} />
        <TouchableOpacity
          activeOpacity={0.5}
          style={[styles.list, styles.row]}
          onPress={() => this.props.onPress()}
        >
          <View style={styles.listLeft}>
            <Image
              source={this.props.img}
              style={{ width: PxToDp(20), height: PxToDp(20) }}
            />
            <Text style={{ marginLeft: PxToDp(10), color: '#2d2e30', fontSize: 17 }}>{this.props.text}</Text>
          </View>
          <View style={styles.row}>
            <Text>{this.props.textName}</Text>
            <Image
              source={require('../../img/next.png')}
            />
          </View>
        </TouchableOpacity>
        <View style={styles.hLine} />
      </View>
    );
  }
}

export default class Mys extends Component {

  constructor(props) {
    super(props);
    this.state = {
      Modelshow: false,
      selectFirmlId: 117,
      // selectFirmlIdBf: 117,
      changshangName: '广汽丰田',
      pEmail: '',
      pStoreName: '',
    };
  }

  _logOut = () => {
    CommonStorage.removeStorage('uid');
    CommonStorage.removeStorage('tpl');
    CommonStorage.removeStorage('factoryId');
    this.props.navigator.resetTo({
      title: 'Login',
      component: Login,
    });
    Request.get({
      url: '/logout',
      accept: 'text',
      success: () => {
      },
      fail: (data) => {
        console.log('logout fail: ', data);
      },
      error: (error) => {
        console.log('logout error: ', error);
      },
    });
  }
  // 意见反馈
  _goAdvice() {
    const dispatch = this.props.dispatch;
    this.props.navigator.push({
      title: 'Feedback',
      passProps: { dispatch },
      component: Feedback,
    });
  }
  // 所在4S店
  _goFoursStore() {
    const { dispatch } = this.props;
    dispatch(fetchStoreInfo(() => {
      this.props.navigator.push({
        title: 'FoursStore',
        name: 'FoursStore',
        component: FoursStore,
        passProps: {
          getStore: (store) => {
            this.setState({ pStoreName: store });
          },
          dispatch,
        },
      });
    }));
  }

  _goEditProfile() {
    this.props.navigator.push({
      title: 'EditProfile',
      name: 'EditProfile',
      component: EditProfile,
    });
  }

  _goModifyEmail() {
    const { dispatch } = this.props;
    const saler = this.props.dealerInfo.saler;
    this.props.navigator.push({
      title: 'ModifyEmail',
      name: 'ModifyEmail',
      component: ModifyEmail,
      passProps: {
        getEmail: (email) => {
          this.setState({ pEmail: email });
        },
        dispatch,
        saler,
      },
    });
  }

  _goModifyPwd() {
    const { dispatch } = this.props;
    const saler = this.props.dealerInfo.saler;
    this.props.navigator.push({
      title: 'ModifyPwd',
      name: 'ModifyPwd',
      component: ModifyPwd,
      passProps: {
        dispatch,
        saler,
      },
    });
  }

  _showChangShang() {
    firmListNew = [];
    if (firmList && firmList.length > 0) {
      firmList.map((item) => {
        firmListNew.push(item.name);
      });
    } else {
      return;
    }
    this._pickerShow(firmListNew, this.state.changshangName, '厂商');
  }

  _pickerShow(list, value, title) {
    Picker.init({
      pickerData: list,
      selectedValue: [value],
      pickerConfirmBtnText: '确认',
      pickerCancelBtnText: '取消',
      pickerTitleText: title,
      pickerBg: [255, 255, 255],
      pickerConfirmBtnColor: [65, 140, 255, 1],
      pickerCancelBtnColor: [139, 140, 142, 1],
      pickerTitleColor: [18, 18, 18, 1],
      pickerToolBarFontSize: 18,
      pickerFontSize: 15,
      onPickerConfirm: (data) => {
        firmList.map((item) => {
          if (item.name === data[0]) {
            this.setState({ changshangName: item.name });
            this.setState({ selectFirmlId: item.id });
            this._comfim(item.id);
          }
        });
      },
      onPickerCancel: (data) => {
        console.log(data);
      },
      onPickerSelect: (data) => {
        console.log(data);
      },
    });
    Picker.show();
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch(fetchProfileAllInfo());
    dispatch(fetchPerformance());
    dispatch(fetchUserInfo((msg) => {
      if (msg && msg.result === 1) {
        this.setState({ pEmail: msg.email });
        this.setState({ pStoreName: msg.storeName });
      }
    }));
  }

  async _comfim(id) {
    this.props.dispatch(fetchFirm(id, (data) => {
      if (data && data.err) {
        DeviceEventEmitter.emit('showToast', data.err);
      } else {
        // 切换厂商，列表，数据，个人信息，业绩重新刷新
        this.props.dispatch(fetchUserInfo());
        this.props.dispatch(fetchPerformance());
        this.props.dispatch(fetchImportOVerview(true));
        this.props.dispatch(fetchSaleList(1, true, false, 1, 0, 0, 0, 0));
        this.props.dispatch(fetchMyCustomerList(1, true, false,
          1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ''));
        this.props.dispatch(fetchOtherList(1, true, false, 1, 0, 0, 0, 0));
        this.props.dispatch(fetchOVerviewChannel('', 1));
      }
    }));
  }

  render() {
    const { userName } = this.props;
    const PerformanceData = this.props.PerformanceData;
    let data = {};
    let name = '';
    let intro = '';
    let avator = '';
    if (PerformanceData && PerformanceData.data) {
      data = PerformanceData.data;
      name = userName || data.cur_user.username;
      if (data.cur_user && data.cur_user.intro) {
        intro = data.cur_user.intro;
      }
      if (PerformanceData.data.cur_user.avatar) {
        avator = `${host}/static/${PerformanceData.data.cur_user.avatar}?t=${(new Date()).getTime()}`;
      }
    }
    return (
      <View style={[styles.flex, styles.container]}>
        <View>
          <View>
            <View style={{ position: 'relative' }}>
              <Image style={styles.myBg} source={require('../../img/home/me-bj.png')}>
                <View style={styles.myBgCon}>

                  <View style={styles.mMsg}>
                    <TouchableOpacity
                      style={styles.mAvator}
                      onPress={() => this._goEditProfile()}
                    >
                      {
                      avator
                      ?
                        <Image
                          style={styles.img}
                          source={{ uri: avator }}
                        />
                      :
                        <Image
                          style={styles.img}
                          source={require('../../img/me-default.png')}
                        />
                    }
                    </TouchableOpacity>
                    <Text style={styles.name}>{name}</Text>
                    <View
                      style={styles.signer}
                      numberOfLines={1}
                    >
                      <Text
                        style={styles.introT}
                        numberOfLines={1}
                      >
                        {this.props.perIntro ? this.props.perIntro : intro}
                      </Text>
                    </View>

                  </View>


                </View>
              </Image>

            </View>
          </View>
        </View>
        <ScrollView>
          <View style={styles.settingWrapper}>
            <List
              text={'所在4s店'}
              bw={PxToDp(1)}
              onPress={() => this._goFoursStore()}
              textName={this.state.pStoreName}
            />
            <List
              text={'厂商'}
              bw={PxToDp(0)}
              onPress={() => this._showChangShang()}
              textName={this.state.changshangName}
            />
          </View>

          <View style={styles.lists}>
            <List
              text={'更改邮箱'}
              bw={PxToDp(1)}
              onPress={() => this._goModifyEmail()}
              textName={this.state.pEmail}
            />
            <List
              text={'更改密码'}
              bw={PxToDp(1)}
              onPress={() => this._goModifyPwd()}
              textName={'********'}
            />
            <List
              text={'意见反馈'}
              bw={PxToDp(1)}
              onPress={() => this._goAdvice()}
              textName={''}
            />
          </View>

          <View style={[styles.hLine, styles.lineTop]} />
          <View>
            <TouchableOpacity
              style={styles.btndefault}
              onPress={() => this._logOut()}
            >
              <View activeOpacity={0.75} >
                <Text style={styles.logoutT}>退出账号</Text>
              </View>
            </TouchableOpacity>
          </View>
          <View style={[styles.hLine, styles.btn]} />
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  row: {
    flexDirection: 'row',
  },
  container: {
    marginTop: Platform.OS === 'ios' ? PxToDp(20) : 0,
    backgroundColor: '#F5F5F5',
  },
  myBg: {
    height: PxToDp(170),
    zIndex: -1,
  },
  myBgCon: {
    zIndex: 999,
    position: 'absolute',
  },
  name: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(18),
    color: '#ffffff',
    marginTop: PxToDp(11),
    backgroundColor: 'transparent',
  },
  signer: {
    width: PxToDp(150),
    maxWidth: PxToDp(150),
    alignItems: 'center',
  },
  introT: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(12),
    color: '#999999',
    marginTop: PxToDp(2),
    maxWidth: PxToDp(150),
    backgroundColor: 'transparent',
  },
  img: {
    height: PxToDp(64),
    width: PxToDp(64),
    borderRadius: PxToDp(32),
  },
  lists: {
    marginTop: PxToDp(20),
    backgroundColor: '#fff',
  },
  list: {
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: PxToDp(16),
    paddingBottom: PxToDp(16),
    paddingLeft: PxToDp(20),
    paddingRight: PxToDp(20),
  },
  listLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  settingWrapper: {
    justifyContent: 'center',
    backgroundColor: '#fff',
    marginTop: PxToDp(20),
    marginBottom: PxToDp(20),
  },
  mMsg: {
    width: '100%',
    alignItems: 'center',
    paddingTop: PxToDp(20),
  },
  mAvator: {
    height: PxToDp(64),
    width: PxToDp(64),
  },
  btn: {
    marginBottom: PxToDp(20),
  },
  btndefault: {
    width: '100%',
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
    height: PxToDp(54),
  },
  logoutT: {
    fontFamily: FontFamilys(),
    color: '#f65252',
    fontSize: PxToDp(16),
  },
  hLine: {
    height: PxToDp(0.5),
    backgroundColor: '#e8e8e8',
    width: '100%',
  },
  lineTop: {
    marginTop: PxToDp(20),
  },
});

